package com.example.neteasemusic.view

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.children


class BottomTabBar(context: Context,attrs:AttributeSet?):ConstraintLayout(context, attrs) {
    private var mSize = 0
    private var lastTabBarItemView:TabBarItemView? = null
    var callback:(Int)->Unit = {}

    override fun onFinishInflate() {
        super.onFinishInflate()
        for (child in children){
            val view = child as TabBarItemView

            if(view.number == 0){
                lastTabBarItemView = view
                view.select()
                callback(0)
            }

            view.callback = {num,tab->
                callback(num)
                lastTabBarItemView!!.cancel()
                lastTabBarItemView = tab
                tab.select()
            }
        }

    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        mSize = width / childCount
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)


        for (i in 0 until childCount) {
            //获取i对应的子控件
            val mChild = getChildAt(i)
            var left = i*mSize
            mChild.layout(left,0,left+mSize,height)
        }
    }


}